package cn.hsa.fqz.monitor.controller;

import cn.hsa.fqz.common.utils.page.PageData;
import cn.hsa.fqz.handler.base.BaseController;
import cn.hsa.fqz.monitor.controller.vo.*;
import cn.hsa.fqz.monitor.entity.*;
import cn.hsa.fqz.monitor.service.MonitorEntityService;
import cn.hsa.fqz.monitor.service.MonitorService;
import cn.hsa.fqz.monitor.service.dto.MonitorBussEntityDTO;
import cn.hsa.fqz.monitor.service.dto.MonitorEntityInstanceDTO;
import cn.hsa.fqz.monitor.service.dto.MonitorExecuteSqlDTO;
import cn.hsa.fqz.monitor.service.dto.TMonitorUserSqlConditionDTO;
import cn.hsa.fqz.task.service.dto.LoginUserDTO;
import cn.hsa.fqz.task.service.dto.TTagSubjectDTO;
import cn.hsa.hsaf.core.framework.context.HsafContextHolder;
import cn.hsa.hsaf.core.framework.util.CurrentUser;
import cn.hsa.hsaf.core.framework.web.WrapperResponse;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.List;
import java.util.Map;

/**
 * @Description TODO
 * @ClassName TTaskTagMonitorController
 * @Author Liu.Jun
 * @Create 2023-10-20 11:06
 * @Version 1.0.0
 */
@Slf4j
@Api(value = "指标监测查询", tags = "指标监测查询")
@RestController
@RequestMapping("/monitor")
@CrossOrigin(value = "*",maxAge = 3600)
public class TMonitorController extends BaseController {


    @Value("${zmjk.ck.monitor.host}")
    private String ckHost;

    @Value("${zmjk.ck.monitor.passwd}")
    private String ckPasswd;

    @Value("${zmjk.ck.monitor.port}")
    private Integer ckPort;

    @Autowired
    private MonitorService monitorService;

    @Autowired
    private MonitorEntityService monitorEntityService;

    @ApiOperation(value = "获取所有指标定义", notes = "获取所有指标定义")
    @PostMapping("/tags")
    public WrapperResponse<List<MonitorTagMinVO>>  getTagsByEnityCode(@RequestBody TagQueryVO vo){
        if(StringUtils.isEmpty(vo.getEntityCode())){
            return WrapperResponse.error(500, "实体编码不能为空", null);
        }
        List<MonitorTagMinVO> dtos = monitorService.getTagsByEnityCode(vo.getEntityCode(),vo.getDimensions(),vo.getTableName());
        return WrapperResponse.success(dtos);
    }

    @ApiOperation(value = "获取所有维度字段定义", notes = "获取所有维度字段定义")
    @PostMapping("/dimension/properties")
    public WrapperResponse<List<MonitorTagMinVO>>  getDimensionPropertiesByEnityCode(@RequestBody TagQueryVO vo){
        if(StringUtils.isEmpty(vo.getEntityCode())){
            return WrapperResponse.error(500, "实体编码不能为空", null);
        }
        List<MonitorTagMinVO> dtos = monitorService.getDimensionPropertiesByEnityCode(vo);
        return WrapperResponse.success(dtos);
    }

    @ApiOperation(value = "通过名称获取主体信息(模糊)", notes = "通过名称获取主体信息(模糊)")
    @PostMapping("/subject")
    public WrapperResponse<List<TTagSubjectDTO>> getTagSubjectByName(@RequestBody TMonitorSubjectVO vo){
        CurrentUser currentUser = HsafContextHolder.getContext().getCurrentUser();
        LoginUserDTO dto = getLoginUser(currentUser);
        String userAcct = dto.getAccount();
        List<TTagSubjectDTO> dtos = monitorService.getTagSubject(ckHost,ckPort,ckPasswd,vo,userAcct);
        return WrapperResponse.success(dtos);
    }

    @ApiOperation(value = "获取所有实体维度信息", notes = "获取所有实体维度信息")
    @GetMapping("/dimensions")
    public WrapperResponse<List<TMonitorDimension>> getDimensionsByEntityCode(@RequestParam("entityCode")String entityCode){
        List<TMonitorDimension> entityList = monitorService.getDimensionsByEntityCode(entityCode);
        return WrapperResponse.success(entityList);
    }

    @ApiOperation(value = "通过实体获取维度信息", notes = "通过实体获取维度信息")
    @GetMapping("/entity/dimensions")
    public WrapperResponse<Map<String,Object>> getDimensionsByEntityCodeAndflag(@RequestParam("entityCode")String entityCode,@RequestParam("defaultFlag")String defaultFlag){
        Map<String,Object> mmp =Maps.newHashMap();
        if(defaultFlag.equals("1")){
            mmp.put("flag", defaultFlag);
            List<TMonitorDimension> entityList = monitorService.getDimensionsByEntityCode(entityCode);
            mmp.put("dimessions", entityList);
        }else{
            mmp.put("flag", defaultFlag);
            List<TMonitorEntityExecuteSql> list = monitorService.getSqlExecuteByTargetEntityCode(entityCode);
            mmp.put("dimessions", list);
        }
        return WrapperResponse.success(mmp);
    }

    @ApiOperation(value = "获取所有实体信息", notes = "获取所有实体信息")
    @GetMapping("/entities")
    public WrapperResponse<List<TMonitorEntity>> getAllEntities(){
        List<TMonitorEntity> entityList = monitorEntityService.getAllEntity();
        return WrapperResponse.success(entityList);
    }

    @ApiOperation(value = "通过编码获取实体信息", notes = "通过编码获取实体信息")
    @PostMapping("/entity/instance")
    public WrapperResponse<MonitorEntityInstanceDTO> getEntityByCode(@RequestBody TagMonitorQueryVO vo){
        MonitorEntityInstanceDTO result = monitorEntityService.getEntityInstinceByCode(ckHost,ckPort,ckPasswd,vo);
        return WrapperResponse.success(result);
    }

    @ApiOperation(value = "获取所有业务分类信息", notes = "获取所有业务分类信息")
    @GetMapping("/buss")
    public WrapperResponse<List<TMonitorBussType>> getAllBuss(){
        List<TMonitorBussType> bussList = monitorEntityService.getAllBussType();
        return WrapperResponse.success(bussList);
    }

    @ApiOperation(value = "获取所有实体信息", notes = "获取所有实体信息")
    @GetMapping("/buss/entity")
    public WrapperResponse<List<MonitorBussEntityDTO>> getEntityByBussCode(@RequestParam("bussCode")String bussCode){
        List<MonitorBussEntityDTO> entityList = monitorEntityService.getEntityByBussCode(bussCode);
        return WrapperResponse.success(entityList);
    }

    @ApiOperation(value = "根据条件查询指标数据", notes = "根据条件查询指标数据")
    @PostMapping("/result")
    public WrapperResponse<List<Map<String,Object>>> getResultWihSqlByCondition(@RequestBody TagMonitorQueryVO vo){
        List<Map<String, Object>> result = Lists.newArrayList();
        /*if(CollectionUtil.isEmpty(vo.getSubjectCode())){
            return WrapperResponse.success(result);
        }else{*/
            try {
                if(CollectionUtil.isEmpty(vo.getTagList())){
                    if(vo.getExecute() == null){
                        String defaultTag = monitorService.getDefaultTag(vo);
                        List<String> ls = Lists.newArrayList();
                        ls.add(defaultTag);
                        vo.setTagList(ls);
                    }else{
                        vo.getTagList().add(vo.getExecute().getDefaultTag());
                    }
                }
                result = monitorService.getStatisticResultWihSqlByCondition(ckHost,ckPort,ckPasswd,vo);
            } catch (ParseException e) {
                return WrapperResponse.fail( "日期时间格式解析失败",null);
            }
            return WrapperResponse.success(result);
        //}
    }

    @ApiOperation(value = "根据条件查询模型数据", notes = "根据条件查询模型数据")
    @PostMapping("/model/result")
    public WrapperResponse<PageData<Map<String,Object>>> getModelResultWihSqlByCondition(@RequestBody TagMonitorQueryVO vo){
        PageData<Map<String, Object>> result = null;
        try {
            result = monitorService.getModelResultWihSqlByCondition(ckHost,ckPort,ckPasswd,vo);
        } catch (ParseException e) {
            return WrapperResponse.fail( "日期时间格式解析失败",null);
        }
        return WrapperResponse.success(result);
    }

    @ApiOperation(value = "根据条件查询模型数据", notes = "根据条件查询模型数据")
    @PostMapping("/model/single/result")
    public WrapperResponse<List<Map<String,Object>>> getSingleModelResultWihSqlByCondition(@RequestBody TagMonitorQueryVO vo){
        List<Map<String,Object>> result = null;
        try {
            result = monitorService.getSingleModelResultWihSqlByCondition(ckHost,ckPort,ckPasswd,vo);
        } catch (ParseException e) {
            return WrapperResponse.fail( "日期时间格式解析失败",null);
        }
        return WrapperResponse.success(result);
    }

    @ApiOperation(value = "根据条件分页查询指标数据-new", notes = "根据条件分页查询指标数据-new")
    @PostMapping("/result/map")
    public WrapperResponse<PageData<Map<String,Object>>> getMapResultWihSqlByCondition(@RequestBody TagMonitorQueryVO vo){
        PageData<Map<String, Object>> result = null;
        try {
            vo.setCurrentUser(false);
            result = monitorService.getMapPageResultWihSqlByCondition(ckHost,ckPort,ckPasswd,vo);
        } catch (ParseException e) {
            return WrapperResponse.fail( "日期时间格式解析失败",null);
        }
        return WrapperResponse.success(result);
    }

    @ApiOperation(value = "根据条件分页查询当前用户指标数据", notes = "根据条件分页查询当前用户指标数据")
    @PostMapping("/result/map/currentUser")
    public WrapperResponse<PageData<Map<String,Object>>> getCurrentUserMapResultWihSqlByCondition(@RequestBody TagMonitorQueryVO vo){
        PageData<Map<String, Object>> result = null;
        CurrentUser currentUser = HsafContextHolder.getContext().getCurrentUser();
        LoginUserDTO dto = getLoginUser(currentUser);
        List<String> subjectCodes = monitorService.getSubjectCodeByAccountAndEntityCode(dto.getAccount(),vo.getEntityCode());
        try {
            vo.setSubjectCode(subjectCodes);
            vo.setCurrentUser(true);
            result = monitorService.getMapPageResultWihSqlByCondition(ckHost,ckPort,ckPasswd,vo);
        } catch (ParseException e) {
            return WrapperResponse.fail( "日期时间格式解析失败",null);
        }
        return WrapperResponse.success(result);
    }

    @ApiOperation(value = "新增个人自选", notes = "新增个人自选")
    @PostMapping("/currentUser/preview")
    public WrapperResponse<Boolean> addCurrentUserPreview(@RequestBody MonitorUserSubjectVO vo){
        Boolean result = false;
        CurrentUser currentUser = HsafContextHolder.getContext().getCurrentUser();
        LoginUserDTO userDTO = getLoginUser(currentUser);
        vo.setUserAcct(userDTO.getAccount());
        vo.setUserAcctId(userDTO.getUid());
        result = monitorService.addCurrentUserPreview(vo);
        return WrapperResponse.success(result);
    }


    @ApiOperation(value = "获取指标监测的字典分类", notes = "获取指标监测的字典分类")
    @GetMapping("/dict/cate")
    public  WrapperResponse<Map<String,String>> getMonitorDict(@RequestParam("entityCode")String entityCode){
        Map<String,String> result = Maps.newHashMap();
       List<TMonitorModelDict> dicts = monitorEntityService.getModelDictByEnityCode(entityCode);
       dicts.forEach( e ->{result.put(e.getDictCode(),e.getDictName());});
       return WrapperResponse.success(result);
    }

    @ApiOperation(value = "根据条件分页查询指标数据", notes = "根据条件分页查询指标数据")
    @PostMapping("/page/result")
    public WrapperResponse<PageData<Map<String,Object>>> getPageResultWihSqlByCondition(@RequestBody TagMonitorQueryVO vo){
        PageData<Map<String, Object>> result = null;
        try {
            result = monitorService.getPageResultWihSqlByCondition(ckHost,ckPort,ckPasswd,vo);
        } catch (ParseException e) {
            return WrapperResponse.fail( "日期时间格式解析失败",null);
        }
        return WrapperResponse.success(result);
    }

    @ApiOperation(value = "获取执行脚本", notes = "获取执行脚本")
    @GetMapping("/sql/entity")
    public WrapperResponse<Object> getSqlExecuteByEntityCode(@RequestParam("entityCode") String entityCode) {
        CurrentUser currentUser = HsafContextHolder.getContext().getCurrentUser();
        LoginUserDTO loginUser = super.getLoginUser(currentUser);
        List<TMonitorEntityExecuteSql> list = monitorService.getSqlExecuteBySourceEntityCode(entityCode);
        log.info("获取脚本信息: " + JSON.toJSONString(list));
        return WrapperResponse.success(list);
    }

    @ApiOperation(value = "执行任务SQL", notes = "执行任务SQL")
    @PostMapping("/execute/sql")
    public WrapperResponse<Object> executeSQL(@RequestBody MonitorExecuteSqlDTO execute) {
        CurrentUser currentUser = HsafContextHolder.getContext().getCurrentUser();
        LoginUserDTO loginUser = super.getLoginUser(currentUser);
        Object obj = null;
        try {
            obj = monitorService.executeSql(loginUser,ckHost,ckPort,ckPasswd,execute,execute.getPage());
        } catch (ParseException e) {
            return WrapperResponse.fail(e.getMessage(), null);
        }
        return WrapperResponse.success(obj);
    }

    @ApiOperation(value = "新增用户脚本条件", notes = "新增用户脚本条件")
    @PostMapping("/user/sql/condition")
    public WrapperResponse<Boolean> addUserSqlCondition(@RequestBody MonitorUserSqlConditionVO vo){
        CurrentUser user = HsafContextHolder.getContext().getCurrentUser();
        LoginUserDTO dto = getLoginUser(user);
        Boolean result = monitorService.addUserSqlCondition(vo, dto);
        return WrapperResponse.success(result);
    }

    @ApiOperation(value = "获取当前登录用户条件配置", notes = "新增用户脚本条件")
    @GetMapping("/current/user/conditions")
    public WrapperResponse<TMonitorUserSqlConditionDTO> getCurrentUserConditions(@RequestParam("entityCode")String entityCode){
        CurrentUser user = HsafContextHolder.getContext().getCurrentUser();
        TMonitorUserSqlConditionDTO dto = monitorService.getCurrentUserConditions(user.getUserAcct(), entityCode);
        return WrapperResponse.success(dto);
    }

    @ApiOperation(value = "获取当前登录用户条件配置", notes = "新增用户脚本条件")
    @CrossOrigin(value = "*",maxAge = 3600)
    @GetMapping("/del/current/user/conditions")
    public WrapperResponse<Boolean> delCurrentUserConditions(@RequestParam("conditionId")Integer conditionId){
        CurrentUser user = HsafContextHolder.getContext().getCurrentUser();
        Boolean result = monitorService.deleteCurrentUserConditions(conditionId);
        return WrapperResponse.success(result);
    }
}
